import axios, { AxiosInstance } from 'axios';

interface MvpConfig {
  baseURL: string;
  apiKey?: string;
}

interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
}

export class MvpClient {
  private client: AxiosInstance;
  private config: MvpConfig;

  constructor(config: MvpConfig) {
    this.config = config;
    this.client = axios.create({
      baseURL: config.baseURL,
      headers: {
        'Content-Type': 'application/json',
        ...(config.apiKey && { 'Authorization': `Bearer ${config.apiKey}` })
      }
    });
  }

  // 用户认证
  async login(username: string, password: string): Promise<ApiResponse<{ token: string }>> {
    try {
      const response = await this.client.post('/auth/login', { username, password });
      return response.data;
    } catch (error) {
      throw this.handleError(error);
    }
  }

  // 获取用户信息
  async getUserProfile(): Promise<ApiResponse<any>> {
    try {
      const response = await this.client.get('/user/profile');
      return response.data;
    } catch (error) {
      throw this.handleError(error);
    }
  }

  // 数据上报
  async reportData(data: any): Promise<ApiResponse<void>> {
    try {
      const response = await this.client.post('/data/report', data);
      return response.data;
    } catch (error) {
      throw this.handleError(error);
    }
  }

  // 获取配置信息
  async getConfig(configKey: string): Promise<ApiResponse<any>> {
    try {
      const response = await this.client.get(`/config/${configKey}`);
      return response.data;
    } catch (error) {
      throw this.handleError(error);
    }
  }

  // 错误处理
  private handleError(error: any): Error {
    if (error.response) {
      return new Error(error.response.data.message || '请求失败');
    }
    return new Error('网络错误');
  }
} 